<?php

namespace App\Model;

use App\BaseModel;
use Illuminate\Support\Facades\DB;

class UserChart extends BaseModel
{
    protected $table = "sys_user_charts";

    public static function updateByDate($date)
    {
        //type      新增用户类型:  0浏览|1订单
        //origin    新增来源:     0其他|1二维码

        $whereSql = ' deleted_at is null and created_at >="'.$date.' 00:00:00" and created_at <="'.$date.' 23:59:59" group by user_id';

        $sql = [];

        //新增用户
        $sql[0] = 'select user_id from sys_new_user_records where '.$whereSql;

        //订单 新增
        $sql[1] = 'select user_id from sys_new_user_records where `type`=1 and '.$whereSql;

        //浏览 新增
        $sql[2] = 'select user_id from sys_new_user_records where `type`=0 and '.$whereSql;

        //浏览 二维码来源新增
        $sql[3] = 'select user_id from sys_new_user_records where `origin`=1 and `type`=0 and '.$whereSql;

        //浏览 其他来源新增
        $sql[4] = 'select user_id from sys_new_user_records where `origin`=0 and `type`=0 and '.$whereSql;

        //订单 二维码来源新增
        $sql[5] = 'select user_id from sys_new_user_records where `origin`=1 and `type`=1 and '.$whereSql;

        //订单 其他来源新增
        $sql[6] = 'select user_id from sys_new_user_records where `origin`=0 and `type`=1 and '.$whereSql;

        $rows = [];

        foreach ($sql as $k=>$v){
            $res = DB::select('select count(user_id) as total from ( '.$v.' ) con');
            $rows[$k] = $res[0];
        }

        $data = [
            'total' => $rows[0]->total,
            'order_total' => $rows[1]->total,
            'view_total' => $rows[2]->total,
            'view_qr_total' => $rows[3]->total,
            'view_other_total' => $rows[4]->total,
            'order_qr_total' => $rows[5]->total,
            'order_other_total' => $rows[6]->total,
        ];

        return UserChart::updateOrCreate(['date'=>$date],$data);
    }
}
